# coding=utf8

import os
import sys
import re

from openpyxl.reader.excel import load_workbook

reload(sys)
sys.setdefaultencoding('utf-8')

PREFIXES = [',', '\'']
SUFFIXES = [':']


def split_symbol(line):
    matched = re.search( r'(\s*)(\[?)([^\[\]]+)(\]?)(\s*)', line, re.M|re.I)
    # print line
    # if str(matched) == 'None':
    #     print line
    #     print "end"

    symbols = matched.group(3)

    buf = []
    parts = []
    i = 0
    while i < len(symbols):
        current = symbols[i]
        n3xt = ''
        if i != len(symbols)-1:
            n3xt = symbols[i+1]
        
        if current in PREFIXES:
            if n3xt in SUFFIXES:
                buf.append(n3xt)
                i = i + 1
            else:
                buf.append(current)
        else:
            if n3xt in SUFFIXES:
                buf.append(current)
                buf.append(n3xt)
                i = i + 1
            else:
                buf.append(current)
            part = ''.join(buf)
            parts.append(part)
            buf = []
        i = i + 1
    return parts


def get_time_quick(line):
    line = line.replace(',', '')
    line = line.replace('\'', '')
    line = line.replace(':', '')
    return len(line)


def process(work_book, course):
    word_sheet_name = "%s_word" % course
    print word_sheet_name
    wb = load_workbook(filename=work_book)
    s1_sheet_name = "%s_s1" % course
    in_ws = wb.get_sheet_by_name(word_sheet_name)
    sheet_names = wb.get_sheet_names()
    if s1_sheet_name in sheet_names:
        out_ws = wb.get_sheet_by_name(s1_sheet_name)
    else:
        out_ws = wb.create_sheet(s1_sheet_name)
    out_row = 2
    print in_ws.max_row
    for r in range(2, in_ws.max_row + 1):
        word_id = in_ws.cell(row=r, column=1).value
        symbol = in_ws.cell(row=r, column=3).value
        parts = split_symbol(symbol)
        for i in range(len(parts)-1, -1, -1):
            out_ws.cell(row=out_row, column=1).value = word_id
            line = ''.join(parts[i:])
            if i == 0:
                out_ws.cell(row=out_row, column=2).value = '[' + line + ']'
            else:
                out_ws.cell(row=out_row, column=2).value = line
            out_ws.cell(row=out_row, column=3).value = 2 * get_time_quick(line)
            out_ws.cell(row=out_row, column=4).value = 4 * get_time_quick(line)
            out_row = out_row + 1
    wb.save(work_book)

